package com.tt.utils.wordUtils.renderplicy;

import com.deepoove.poi.data.PictureRenderData;
import com.deepoove.poi.policy.AbstractRenderPolicy;
import com.deepoove.poi.render.RenderContext;
import com.tt.utils.wordUtils.entity.ImageContent;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.util.List;
import java.util.UUID;

/**
 * 基于 AbstractRenderPolicy 的图片渲染策略
 * 支持：URL + 本地路径、按最大宽度缩放、图片居中
 */
public class ImageRenderPolicy extends AbstractRenderPolicy<ImageContent> {

    @Override
    public void doRender(RenderContext<ImageContent> context) throws Exception {
        ImageContent data = context.getData();
        if (data == null) {
            return;
        }
        List<ImageContent.ImageBody> imageList = data.getImageBody();
        for (int i = 0; i < imageList.size(); i++) {
            insertImage(context.getRun(), imageList.get(i));
            if (i < imageList.size() - 1) {
                // 每张图片单独一段，避免挤在一起
                XWPFParagraph newPara = context.getRun().getDocument().createParagraph();
                newPara.setAlignment(ParagraphAlignment.CENTER);
            }
        }
    }

    private void insertImage(XWPFRun run, ImageContent.ImageBody picture) throws Exception {
        if (picture == null || picture.getImageUrl() == null) {
            return;
        }

        PictureRenderData smartPicture = PoiPictureUtils.createSmartPicture(picture.getImageUrl(), PoiPictureUtils.PictureSourceType.URL);

        try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(smartPicture.readPictureData())) {
            BufferedImage img = ImageIO.read(new ByteArrayInputStream(smartPicture.readPictureData()));
            int width = img.getWidth();
            int height = img.getHeight();

            // Word 最大宽度（EMU）
            double maxWidthEMU = Units.toEMU(picture.getWidth() * 28.35);
            double imgWidthEMU = Units.pixelToEMU(width);
            double imgHeightEMU = Units.pixelToEMU(height);

            // 如果图片宽度超过最大宽度，按比例缩放
            if (imgWidthEMU > maxWidthEMU) {
                double ratio = maxWidthEMU / imgWidthEMU;
                imgWidthEMU *= ratio;
                imgHeightEMU *= ratio;
            }

            String uuid = UUID.randomUUID().toString();
            run.addPicture(byteArrayInputStream, smartPicture.getPictureType().type(), uuid,
                    (int) imgWidthEMU, (int) imgHeightEMU);

            // 图片居中
            XWPFParagraph paragraph = (XWPFParagraph) run.getParent();
            paragraph.setAlignment(ParagraphAlignment.CENTER);
        }
    }

    @Override
    protected void afterRender(RenderContext<ImageContent> context) {
        clearPlaceholder(context, true);
    }
}
